package com.jyw.business.obstacles.websocket.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 沈峻
 * @ClassName WsSessionManager
 * @Description TODO
 * @Date 2023/8/21 14:38
 **/
@Slf4j
public class WsSessionManager {

    /**
     * 保存连接 session 的地方
     */
    private static ConcurrentHashMap<Long, WebSocketSession> SESSION_POOL = new ConcurrentHashMap<>();

    /**
     * 添加 session
     *
     * @param key
     */
    public static void add(Long key, WebSocketSession session) {
        // 添加 session
        SESSION_POOL.put(key, session);
    }

    /**
     * 删除 session,会返回删除的 session
     *
     * @param key
     * @return
     */
    public static WebSocketSession remove(Long key) {
        // 删除 session
        return SESSION_POOL.remove(key);
    }

    /**
     * 删除并同步关闭连接
     *
     * @param key
     */
    public static void removeAndClose(Long key) {
        WebSocketSession session = remove(key);
        if (session != null) {
            try {
                // 关闭连接
                session.close();
            } catch (IOException e) {
                // todo: 关闭出现异常处理
                e.printStackTrace();
            }
        }
    }

    /**
     * 获得 session
     *
     * @param key
     * @return
     */
    public static WebSocketSession get(Long key) {
        // 获得 session
        return SESSION_POOL.get(key);
    }

    /**
     * 返回所有连接的session
     *
     * @return
     */
    public static Collection<WebSocketSession> getAll() {
        return SESSION_POOL.values();
    }
    //关闭连接
    public static void remove(WebSocketSession session) {
        for (Map.Entry<Long, WebSocketSession> entry : SESSION_POOL.entrySet()) {
            if(entry.getValue().equals(session)){
                SESSION_POOL.remove(entry.getKey());
            }
        }
    }
}
